#include "TcpClient.hpp"


using namespace TcpClientArea;

struct sockaddr_in server;

static int sockfd;


void ClientQuit(int signo)
{
    (void)signo;
    std::string message = "quit";
    int n = ::send(sockfd,message.c_str(),message.size(),0);
    if(n<0)
    {
        LOG(LogLevel::ERROR)<<"send error";
        DIE(SEND_ERR);
    }

    exit(0);
}


//./TcoClient <server_ip> <server_port>
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " <server_ip> <server_port>" << std::endl;
        return 1;
    }

    ::signal(2,ClientQuit);

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    //创建套接字
    sockfd = ::socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        LOG(LogLevel::FATALER)<<"socket error";
        DIE(SOCKET_ERR);
    }

    //填充信息
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(server_port);
    server.sin_addr.s_addr = ::inet_addr(server_ip.c_str());


    //链接
    int n = ::connect(sockfd,CONV(&server),sizeof(server));
    if(n<0)
    {
        LOG(LogLevel::FATALER)<<"connect error";
        DIE(CONNECT_ERR);
    }

    while(true)
    {
        std::cout<<"Please Enter: ";
        std::string message;
        std::getline(std::cin,message);

        char buffer[1024];

        //向服务器写消息
        int n = ::send(sockfd,message.c_str(),message.size(),0);
        if(n>0)
        {
            int m = ::recv(sockfd,buffer,sizeof(buffer)-1,0);
            if(m>0)
            {
                buffer[m] = 0;
                std::cout<<buffer<<std::endl;
            }
            else break;
        }
        else break;
    }

    ::close(sockfd);
    return 0;
}